import { Workbook } from 'exceljs'

/**
 * excel 导出
 * style:excel表的样式配置
 * tableData:表的数据内容
 * headerColumns:表头配置
 * sheetName：工作表名
 */
export const excelJsExport = async ({ sheetName, headerColumns, tableData }) => {
    // 创建工作簿
    const workbook = new Workbook()
    workbook.creator = 'maysham'
    workbook.created = new Date()

    // 添加工作表
    const worksheet = workbook.addWorksheet(sheetName)

    if (headerColumns.length > 0) {
        // 设置列头
        const columnsData = headerColumns.map((column, index) => {
            const width = column.width
            return {
                header: column.title,
                key: column.key,
                width: isNaN(width) ? 20 : width / 10
            }
        })
        worksheet.columns = columnsData
        // 设置表头样式
        const headerRow = worksheet.getRow(1)
        headerRow.alignment = { horizontal: 'center' }
        headerRow.font = { bold: true };
        headerRow.border
    }
    // 设置行数据
    if (tableData.length > 0) {
        // 将传入的数据格式化为exceljs可使用的数据格式
        const data = []
        tableData.forEach((table) => {
            let obj = {}
            headerColumns.forEach((header) => {
                obj[header.key] = table[header.key]
            })
            data.push(obj)
        })

        // 添加行
        if (data) worksheet.addRows(data)
    }

    return await workbook.xlsx.writeBuffer()
}


export const userExcelHeader = [
    {
        title: '用户序号',
        dataIndex: 'user_id',
        width: 80
    },
    {
        title: '登录名称',
        dataIndex: 'user_name'
    },
    {
        title: '用户邮箱',
        dataIndex: 'email',
        width: 240
    },
    {
        title: '手机号码',
        dataIndex: 'phonenumber'
    },
    {
        title: '用户性别',
        dataIndex: 'sex'
    },
    {
        title: '帐号状态',
        dataIndex: 'status'
    },
    {
        title: '最后登录IP',
        dataIndex: 'login_ip'
    },
    {
        title: '最后登录时间',
        dataIndex: 'login_date'
    },
    {
        title: '部门名称',
        dataIndex: 'dept.dept_name'
    },
    {
        title: '部门负责人',
        dataIndex: 'dept.leader'
    }
]

export function downloadFile(buffer, filename) {
    let url = window.URL.createObjectURL(new Blob([buffer], { type: 'arrayBuffer' }))
    const link = document.createElement('a')
    link.style.display = 'none'
    link.href = url;
    link.setAttribute('download', filename)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
}